package com.hty.filetrans;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

public class MainActivity extends Activity {
    static final int FILE_CODE = 0, REQUEST_PERMISSION_CODE = 1;
    TextView textView_local;
    EditText editText_IP, editText_port, editText_remotePath, editText_message, editText;
    Button button_add, button_remotePath_root, button_remotePath_MIUITV_album, button_clear, button_send;
    Handler handler;
    SocketManager socketManager;
    InputMethodManager IMM;
    ProgressBar progressBar;
    SimpleDateFormat SDF = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
    private final String[] PERMISSIONS = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        IMM = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);

        textView_local = (TextView) findViewById(R.id.textView_local);
        editText_IP = (EditText) findViewById(R.id.editText_IP);
        editText_port = (EditText) findViewById(R.id.editText_port);

        editText_remotePath = (EditText) findViewById(R.id.editText_remotePath);

        button_remotePath_root =  (Button) findViewById(R.id.button_remotePath_root);
        button_remotePath_root.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                editText_remotePath.setText("");
            }
        });

        button_remotePath_MIUITV_album =  (Button) findViewById(R.id.button_remotePath_MIUITV_album);
        button_remotePath_MIUITV_album.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                editText_remotePath.setText("ScreenCapture");
            }
        });

        editText_message = (EditText) findViewById(R.id.editText_message);
        //editText_message.setMovementMethod(ScrollingMovementMethod.getInstance());

        editText = (EditText) findViewById(R.id.editText);
        button_send =  (Button) findViewById(R.id.button_send);
        button_send.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                String s = editText.getText().toString();
                if (s.equals(""))
                    return;
                editText.setText("");
                String IP = editText_IP.getText().toString();
                final int port = Integer.parseInt(editText_port.getText().toString());
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        socketManager.sendText(s, IP, port);
                    }
                });
                thread.start();
            }
        });

        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        button_add = (Button) findViewById(R.id.button_add);
        button_add.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                IMM.hideSoftInputFromWindow(editText_port.getWindowToken(), 0);
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("*/*");
                intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); //打开多个文件
                startActivityForResult(intent, FILE_CODE);
            }
        });

        button_clear = (Button) findViewById(R.id.button_clear);
        button_clear.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
               editText_message.setText("");
            }
        });

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0:
                        editText_message.setText("[" + SDF.format(new Date()) + "] " + msg.obj.toString() + "\n" + editText_message.getText().toString());
                        break;
                    case 1:
                        textView_local.setText("本机，IP：" + getIP() + "，port:" + msg.obj.toString());
                        editText_IP.setText(getIP());
                        editText_port.setText(msg.obj.toString());
                        break;
                    case 2:
                        Toast.makeText(getApplicationContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
                        break;
                    case 3:
                        String path = msg.obj.toString();
                        MediaScannerConnection.scanFile(MainActivity.this, new String[] { path }, null, null);
                        break;
                    case 4:
                        int m = (int) msg.obj;
                        progressBar.setMax(m);
                        progressBar.setVisibility(View.VISIBLE);
                        break;
                    case 5:
                        int p = (int) msg.obj;
                        progressBar.setProgress(p);
                        break;
                    case 6:
                        progressBar.setVisibility(View.GONE);
                        break;
                }
            }
        };
        socketManager = new SocketManager(handler);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(PERMISSIONS, REQUEST_PERMISSION_CODE);
            }
        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String action = intent.getAction();
        String type = intent.getType();
        Log.e(Thread.currentThread().getStackTrace()[2] + "", type);
        if (action.equals(Intent.ACTION_SEND) || action.equals(Intent.ACTION_SEND_MULTIPLE)) {
           send(intent);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == FILE_CODE && resultCode == Activity.RESULT_OK) {
            send(intent);
        }
    }

    void send(Intent intent) {
        final String IP = editText_IP.getText().toString();
        final int port = Integer.parseInt(editText_port.getText().toString());
        if (IP.equals(getIP())) {
            Toast.makeText(getApplicationContext(), "不需要发给自己！", Toast.LENGTH_SHORT).show();
            return;
        }

        ClipData CD = intent.getClipData();
        Log.e(Thread.currentThread().getStackTrace()[2] + "", CD + "");
        final ArrayList<String> AL_filename = new ArrayList<>();
        final ArrayList<String> AL_filepath = new ArrayList<>();
        if (CD == null) {
            Uri uri = intent.getData();
            String suri = uri.toString();
            Log.e(Thread.currentThread().getStackTrace()[2] + "", suri);
            String[] proj = { MediaStore.Files.FileColumns.DATA };
            Cursor cursor = managedQuery(uri, proj, null, null, null);
            int index = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
            Log.e(Thread.currentThread().getStackTrace()[2] + "", index + "");
            if (index != -1) {
                cursor.moveToFirst();
                String filepath = cursor.getString(index);
                Log.e(Thread.currentThread().getStackTrace()[2] + "", filepath);
                String remotePath = editText_remotePath.getText().toString();
                String filename;
                if (remotePath.equals(""))
                    filename = filepath.substring(filepath.lastIndexOf("/") + 1);
                else
                    filename = remotePath + filepath.substring(filepath.lastIndexOf("/"));
                Log.e(Thread.currentThread().getStackTrace()[2] + "", filename);
                AL_filename.add(filename);
                AL_filepath.add(filepath);
            }  else {
                editText_message.setText("[" + SDF.format(new Date()) + "] 无法解析 " + suri + "\n" + editText_message.getText().toString());
                return;
            }
        } else {
            int count = CD.getItemCount();
            for (int i = 0; i < count; i++) {
                Uri uri = CD.getItemAt(i).getUri();
                if (uri != null) {
                    String suri = uri.toString();
                    String remotePath = editText_remotePath.getText().toString();
                    String filepath = "", filename="";
                    if (suri.startsWith("content://")) {
                        String[] proj = { MediaStore.Files.FileColumns.DATA };
                        Cursor cursor = managedQuery(uri, proj, null, null, null);
                        int index = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
                        Log.e(Thread.currentThread().getStackTrace()[2] + "", index + "");
                        if (index != -1) {
                            cursor.moveToFirst();
                            filepath = cursor.getString(index);
                        } else {
                            editText_message.setText("[" + SDF.format(new Date()) + "] 无法解析 " + suri + "\n" + editText_message.getText().toString());
                            return;
                        }
                    } else if (suri.startsWith("file://")) {
                        try {
                            filepath = URLDecoder.decode(suri, "UTF-8");
                            filepath = filepath.substring(7);
                        } catch (Exception e) {
                            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
                        }
                    }
                    if (remotePath.equals(""))
                        filename = filepath.substring(filepath.lastIndexOf("/") + 1);
                    else
                        filename = remotePath + filepath.substring(filepath.lastIndexOf("/"));
                    AL_filename.add(filename);
                    AL_filepath.add(filepath);
                }
            }
        }
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                socketManager.sendFile(AL_filename, AL_filepath, IP, port);
            }
        });
        thread.start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 0, 0, "退出");
        menu.add(0, 1, 1, "关于");
        menu.add(0, 2, 2, "更新日志");
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int item_id = item.getItemId();
        switch (item_id) {
            case 0:
                finish();
                break;
            case 1:
                new AlertDialog.Builder(this)
                        .setIcon(R.mipmap.ic_launcher)
                        .setTitle("海天鹰文件传输 V2.0")
                        .setMessage("通过 Socket 收发文件。\n作者：海天鹰\nQQ：84429027\n参考：https://www.cnblogs.com/zhujiabin/p/7139644.html")
                        .setPositiveButton("确定", null).show();
                break;
            case 2:
                new AlertDialog.Builder(this)
                        .setIcon(R.mipmap.ic_launcher)
                        .setTitle("更新日志")
                        .setMessage("V2.0 (2022-11)\n1.增加收发文字。\n\nV1.1 (2022-03)\n1.增加以分享方式发送文件，uri 兼容 content:// 和 file://，修复解析不了崩溃的问题。\n2.构建JSON保存文件名和文件时间，文件接收完成后修改文件时间。\n\nV1.0 (2021-01)\nSocket收发文件，支持设置上传路径。")
                        .setPositiveButton("确定", null).show();
                break;
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.exit(0);
    }

    public String getIP() {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int i = wifiInfo.getIpAddress();
        return (i & 0xFF) + "." +
                ((i >> 8 ) & 0xFF) + "." +
                ((i >> 16 ) & 0xFF)+ "." +
                ((i >> 24 ) & 0xFF );
    }

}